<?php

/**
 * 验证码类
 */
class Code
{
	public $config=[
		'width'=>200,
		'heigth'=>100,
		'length'=>4,
		'is_line'=>0,
		'str'=>"qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM"
	];//配置

	public $src;//画布

	public function __get($name)
	{
		return $this->config[$name];
	}
	
	public function __construct($config=array())
	{
		$this->config = array_merge($this->config,$config);
	}

	public function entry()
	{
		
		$this->_create();
		// 创建画布
		// 填充颜色
		// 画干扰
		// 画线
		$this->_line();
		// 画点
		// 画字
		$this->_addfont();
		// 输出
		$this->_out();
	}

	protected function _create($value='')
	{
		// // 1  创建画布
		$this->src = imageCreateTrueColor($this->width,$this->heigth); 

		// // 2  选择颜色
		$color = imageColorAllocate($this->src,255,255,255);

		// // 3  填充画布

		imageFill($this->src,0,0,$color);
	}

	protected function _line()
	{
		for ($i=0; $i < $this->is_line; $i++) { 
			$color = imageColorAllocate($this->src,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));

			$x = mt_rand(0,$this->width);
			$y = mt_rand(0,$this->heigth);
			$x1 = mt_rand(0,$this->width);
			$y1 = mt_rand(0,$this->heigth);

			imageline ($this->src, $x ,$y , $x1, $y1 , $color);
		}
	}

	public function _addfont()
	{
		for ($i=0; $i <$this->length ; $i++) { 

			$color = imageColorAllocate($this->src,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));

			$text = $this->str[mt_rand(0,strlen($this->str)-1)];

			$fontsize = 0.6*$this->heigth;

			$y = ($this->heigth+$fontsize)/2;

			$diff = ($this->width/$this->length)-$fontsize > 0 ? ($this->width/$this->length)-$fontsize : 0;

			$x = ($this->width/$this->length)*$i+($diff)/2;

			imagettftext ($this->src, $fontsize , mt_rand(-15,15), $x , $y ,$color , LIB_PATH.'/Alpha Thin.ttf' , $text);
		}
	}

	public function _out()
	{
		// 6  保存/输出
		header("Content-type: image/png");
		// imagepng($src,"./img/".uniqid().'.png');
		imagepng($this->src);
	}
}